<template>
	<SecondTitle title="出入口拥挤统计" />
	<div class="pipe">
    <Echarts v-if="entranceCodes.length>0" :options="option()" :height="540" />
	</div>
</template>
<script lang="ts" setup>
	import { ref, onMounted } from 'vue'
	import * as echarts from 'echarts'
	import { getEntranceCrowdStatistical } from '@/api/train'
  import dayjs from 'dayjs'

  let option = () => {
	}
	const list: any = ref();
	const chartData: any = ref([])
	const entranceCodes: any = ref([])

	onMounted(async () => {
    const curDate = dayjs(new Date()).format('YYYY-MM-DD');
    await getEntranceCrowdStatistical(curDate).then((resData: any) => {
      chartData.value = resData.data;
      // 获取所有入口名称
      entranceCodes.value = Object.keys(chartData.value);
      console.log("chartData.value is ", chartData.value);
      option = () => {
        console.log("option.option is ");

        console.log("entranceCodes.value is ", entranceCodes.value);
        // 获取所有拥堵等级名称（从第一个入口的数据中提取）
        const congestionLevels = chartData.value[entranceCodes.value[0]].map((item: any) => item.congestionLevelName);
        
        // 准备原始数据
        let rawData = [];
        for (let level of congestionLevels) {
          let levelData = [];
          for (let entrance of entranceCodes.value) {
            // 找到对应拥堵等级的数据
            const dataItem = chartData.value[entrance].find((item: any) => item.congestionLevelName === level);
            levelData.push(dataItem ? dataItem.count : 0);
          }
          rawData.push(levelData);
        }
        
        // 计算每个入口的总数
        let totalData = [];
        for (let i = 0; i < entranceCodes.value.length; i++) {
          let sum = 0;
          for (let j = 0; j < rawData.length; j++) {
            sum += rawData[j][i];
          }
          totalData.push(sum);
        }

        // 创建系列数据
        const series = congestionLevels.map((name: any, index: number) => {
          return {
            name,
            type: 'bar',
            stack: 'total',
            barWidth: '70%',
            // label: {
            //   show: true,
            //   position: 'inside',
            //   formatter: function(params: any) {
            //     // 显示格式为：拥堵等级名称：数量
            //     return `${name}:${params.value}`;
            //   },
            //   fontSize: 12,
            //   fontWeight: 'bold',
            //   color: '#fff'
            // },
            data: rawData[index].map((count, idx) => {
              return {
                value: count,
                total: totalData[idx] // 存储总数用于计算百分比
              };
            })
          };
        });
        // 配置项
        const opt = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: function(params: any) {
              // 获取当前柱子对应的入口名称
              const entranceName = params[0].name;
              // 获取当前柱子的总数
              const total = params[0].data.total;
              
              // 构建tooltip内容
              let html = `<div style="font-size:14px;font-weight:bold;margin-bottom:10px">${entranceName}</div>`;
              
              // 遍历所有系列（拥堵等级）
              params.forEach((param: any) => {
                const value = param.value;
                const percent = total > 0 ? Math.round(value / total * 100) : 0;
                html += `
                  <div style="display:flex;align-items:center;margin-bottom:5px">
                    <span style="display:inline-block;width:10px;height:10px;background:${param.color};border-radius:50%;margin-right:8px"></span>
                    <div>
                      <span style="font-weight:bold">${param.seriesName}:</span> 
                      ${value} (${percent}%)
                    </div>
                  </div>
                `;
              });
              
              html += `<div style="margin-top:10px;padding-top:5px;border-top:1px solid rgba(255,255,255,0.2);">
                        <span style="font-weight:bold">总数:</span> ${total}
                      </div>`;
              
              return html;
              // const data = params[0];
              // const total = data.data.total;
              // const percent = total > 0 ? Math.round(data.value / total * 100) : 0;
              // return `${data.name}<br/>
              //         ${data.seriesName}: ${data.value} (${percent}%)<br/>
              //         总数: ${total}`;
            }
          },
          legend: {
            data: congestionLevels,
            top: 0,
            itemWidth: 30,
            itemHeight: 16,
            textStyle: {
              fontSize: 25,
              color: '#fff'
            }
          },
          grid: {
            left: '5%',
            right: '4%',
            bottom: '15%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: entranceCodes.value,
            axisLabel: {
              interval: 0,
              rotate: 30,
              fontSize: 25,
              color: '#fff'
            }
          },
          yAxis: {
            type: 'value',
            name: '数量',
            nameTextStyle: {
              padding: [0, 0, 0, 30]
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          series: series
        };
        return opt;
      };
    });

	});
</script>

<style lang="scss" scoped>
	.pipe {
		margin-top: 10px;
	}
</style>
